<?php
/**
 * peck 模板类  
 *
 * @filesource pView.class.php
 * @package peck
 * @subpackage 
 * @version $id: 0.2, utf8, Fri Jan  1 15:30:11 CST 2010
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2010 MiFunny China Inc.
 * @link http://mifunny.info/
 * @see example: testView.php 
 */

class _view{
    private static $instance;
    //private $_tp = null; //模板根目录
    //private $_content = null; //最后显示的内容

    /**
     * 变量数组
     *  TEMPLATEPATH 模板根目录
     *
     * @var array
     */
    private $_vars = array(
        'TEMPLATEPATH' => null,
        );

   /**
    * 初始化 模板引擎
    *
    * @param string 模板根目录 
    */
   public function __construct($template_path = null){
        if( is_string($template_path) ){
            $this->_vars['TEMPLATEPATH'] = $template_path;
        }
        self::$_instance = $this;
   }

   /**
    * 重写魔法方法 __set 和 __get
    *
    * @param string $key
    * @param mixed $value
    */ 
   public function __set($key, $value){
        $this->_vars[$key] = $value;
   }

   public function __get($key){
        return $this->_vars[$key];
   }

   /**
    * 获得最后的显示信息
    *
    * @param string $template 模板文件全名
    */
   public function fetch($template){
       //目录分隔符
       defined('DS') or define('DS', DIRECTORY_SEPARATOR);
       //模板根目录
       defined('TP') or define('TP', empty($this->_vars['TEMPLATEPATH']) ? '' : rtrim($this->_vars['TEMPLATEPATH'], '\\/').DS );

       $template = TP.str_replace('/', DS,  $template);
       if( is_file($template) ){
           unset( $this->_vars['TEMPLATEPATH'] );
           extract($this->_vars, EXTR_OVERWRITE);

           $errno = error_reporting();
           error_reporting($errno & ~E_NOTICE);
           ob_start();
           include($template);
           $content = ob_get_contents();
           ob_end_clean();
           error_reporting($errno);

           return $content;
       }else{
           throw new LogicException('('.__METHOD__.')'.'Error: '.$template.' is not a file !');
           return false;
       }
   }

   public function display($template){
       echo $this->fetch($template);
   }

   /**
    * 获得静态视图对像
    *
    * @return object DsTemplate
    */
   public static function instance(){
       if( !(self::$instance instanceof self) ){
           new self();  // self::$_instance = new self();
       }
       return self::$instance;
   }
   
   public static function object(){
   		return self::instance();
   }

   /**
    * 静态方法, 显示视图
    *
    * @param string $template 模板文件
    * @param array $vars 变量数组
    */
   public static function show($template, array $vars=null){
       $view = self::instance();
       //$view->TEMPLATEPATH = $template_path;
       if( !empty($vars) ){
           $view->_vars = $vars;
       }  
       $view->display($template); 
   }

}//END class DsTemplate
?>